﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;

namespace Business
{
    /// <summary>
    /// cookies帮助类
    /// </summary>
    public class CookiesHelper : ControllerBase
    {
        public HttpContext _httpContext;
        public CookiesHelper(HttpContext httpContext)
        {
            _httpContext = httpContext;
        }
        /// <summary>
        /// 保存cookies 并设置过期时间（分钟）
        /// </summary>
        /// <param name="key">cookies名</param>
        /// <param name="value">cookies值</param>
        /// <param name="time">过期时间（分钟）</param>
        public void SaveCookiesValue(string key, string value, int time)
        {
            CookieOptions cookieOptions = new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(time)
            };
            _httpContext.Response.Cookies.Append(key, value, cookieOptions);
        }

        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">cookies名</param>
        /// <returns></returns>
        public string GetCookiesValue(string key)
        {
            _httpContext.Request.Cookies.TryGetValue(key, out string value);
            return value;
        }

        /// <summary>
        /// 删除cookies
        /// </summary>
        /// <param name="key">cookies名</param>
        public void DeleteCookies(string key)
        {
            _httpContext.Response.Cookies.Delete(key);
        }
    }
}
